<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>Title</title>
    <link rel="stylesheet" href="../static/plugins/layui/css/layui.css">
    <link rel="stylesheet" href="../static/plugins/layui/css/formSelects-v4.css">
</head>
<style>
    .ok-body {
        padding: 10px
    }
    .tip {
        margin-left: 120px;
        margin-top: 20px;
        font-size: larger;
    }
</style>

<body>
<div class="ok-body">

    <blockquote class="layui-elem-quote layui-text">
        巡检计划
    </blockquote>

    <form class="layui-form" action="">
        <div class="layui-form-item">
            <input type="hidden" name="id" id="id" th:value="${id}">
            <label class="layui-form-label">计划名称</label>
            <div class="layui-input-inline">
                <input type="text" name="name" lay-verify="required" autocomplete="off" class="layui-input">
            </div>
            <div class="layui-form-mid layui-word-aux">必填</div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">描述</label>
            <div class="layui-input-inline">
                <input type="text" name="description" autocomplete="off" class="layui-input">
            </div>
        </div>


        <div class="layui-form-item">
            <label class="layui-form-label">巡检指令</label>

            <div id="order" class="orderDetails">

                <div class="layui-inline">
                    <div class="layui-input-inline">
                        <select name="modelId" lay-verify="required" index="0" lay-filter="modelId">
                            <option value="">选择设备类型</option>
                        </select>
                    </div>
                </div>
                <!--<label class="layui-form-label">计划周期</label>-->
                <div class="layui-inline">
                    <div class="layui-input-inline">
                        <select name="devicePartId" lay-verify="required" index="0" lay-filter="devicePartId">
                            <option value="">选择巡检部位</option>
                        </select>
                    </div>
                </div>

                <div class="layui-inline">
                    <div class="layui-input-inline">
                        <input type="text" name="content" placeholder="维护内容" lay-verify="required" autocomplete="off" index="0" class="layui-input">
                    </div>
                </div>
            </div>

            <div class="layui-inline" style="  float: left; margin-left: 760px;margin-top: -39px;">
                <input type="button" name="addOrder" value="添加指令" class="layui-btn layui-btn-sm layui-btn-normal">
                <input type="button" name="deleteOrder" value="删除指令" class="layui-btn layui-btn-sm layui-btn-danger">
            </div>

        </div>


        <div class="layui-form-item">
            <label class="layui-form-label">计划时间</label>
            <div class="layui-input-inline">
                <input type="text" id="planTime" name="planTime" lay-verify="required" placeholder="巡检计划具体时间" autocomplete="off"
                       class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">执行周期</label>
            <div class="layui-inline">
                <div class="layui-input-inline">
                    <select name="cycleType" lay-verify="required" lay-filter="cycle">
                        <option value="1">每天</option>
                        <option value="2">每周</option>
                        <option value="3">每月</option>
                        <option value="4">半年</option>
                        <option value="5">每年</option>
                    </select>
                </div>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">计划执行人</label>
            <div class="layui-input-inline">
                <select name="operatorId" lay-verify="required" lay-filter="operactorId">
                    <option value="">请选择设执行人</option>
                </select>
            </div>
            <div class="layui-form-mid layui-word-aux">必选</div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">状态</label>
            <div class="layui-input-inline">
                <input type="checkbox" checked="" name="status" lay-skin="switch" value="1" lay-filter="switchTest" lay-text="启用|禁用">
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit="" lay-filter="submit">立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>

    </form>

</div>

<script src="../static/plugins/layui/layui.js"></script>
<script src="../static/js/jquery-3.2.1.min.js"></script>
<script src="../static/js/jquery.base64.js"></script>
<script src="../static/js/device.js"></script>

<script th:inline="none">
    layui.use(['form', 'laydate', 'util'], function () {
        var form = layui.form;
        var util = layui.util;
        var laydate = layui.laydate;
        var tableName = 'cycleTask';
        var id = $('#id').val();

        laydate.render({
            elem: '#planTime'
            , type: 'datetime'
            , min: 0
            , format: 'yyyy-MM-dd HH:mm'
        });

        //监听设备类型，获取该设备类型下面的所有部位信息
        form.on('select(modelId)', function (data) {
            var index = $(data.elem).attr('index');
            var inputSelectStr = 'select[name="devicePartId"][index='+index+']';
            var devicePartSelector = $(inputSelectStr);
            devicePartSelector.empty();
            devicePartSelector.append('<option value="">选择巡检部位</option>');
            JJZ.initSelectWithParam(devicePartSelector, '/devicePart/dataGridByModelId','modelId='+data.value, function (noError) {
                form.render(); //更新表单
            });
        });


        //监听选择的设备类型，根据设备类型来初始化多选零件数据
        form.on('select(devicePartId)', function (data) {
            var index = $(data.elem).attr('index');
            // console.log($(data.elem).find('option:selected').data());
            var inputSelect = 'input[name=content][index='+index+']';
            $(inputSelect).val($(data.elem).find('option:selected').data().description)
        });

        if (id) {
            //表示是修改页面,名称不能修改
            JJZ.named('name').attr('readonly', 'readonly').css('border','none');

            var param = 'current=1&pageSize=2&searchCol=id&searchValue=' + id;
            JJZ.requestTableData(tableName, param, function (data) {
                var result = data.records[0];
                JJZ.named('name').val(result.name);
                JJZ.named('description').val(result.description);
                //初始化计划时间
                JJZ.named('planTime').val(JJZ.FormatDate(result.planTime, 'yyyy-MM-dd HH:mm'));
                result.status == 1? '': JJZ.named('status').removeAttr("checked");
                //初始化计划指令
                var orderList = JSON.parse(result.content);

                //这里初始化了所有的额设备型号，设备部位的下拉
                addOrderDetail(orderList);

                //初始化计划执行人下拉框
                JJZ.initSelectShowField(JJZ.named('operatorId'), '/user/dataGrid', 'username', function (noError) {
                    if (noError) {
                        JJZ.named('operatorId').find('option').each(function (index, elem) {
                            $(elem).val() == result.operatorId ? $(elem).attr("selected", "selected") : '';
                        })
                        form.render();
                    }
                });
            });

        } else {

            //初始化设备型号下拉框
            JJZ.initSelect(JJZ.named('modelId'), '/model/dataGrid', function (noError) {
                form.render();
            });
            //初始化计划执行人下拉框
            JJZ.initSelectShowField(JJZ.named('operatorId'), '/user/dataGrid', 'username', function (noError) {
                form.render();
            });

        }

        form.on('submit(submit)', function (data) {

            var obj = {};
            var cycleType = data.field['cycle'];
            var timeArr = [];
            var cron = initCron(cycleType);
            obj.id = data.field['id'];
            obj.name = data.field['name'];
            obj.description = data.field['description'];
            obj.cron = cron;
            obj.cycleType = cycleType;
            obj.planTime = data.field['planTime'];
            obj.cycleStr = timeArr.join(",");

            obj.status = data.field['status'] == 1 ? 1 : 0;
            obj.content = initCycleTaskContent();
            obj.operactorId = data.field['operactorId'];

            // if(id){
            //     //编辑
            //     JJZ.editData(tableName, obj, function (data) {
            //         window.location.href =JJZ.baseUrl+ '/' + tableName + '/cycleTaskDataGrid';
            //     });
            // }else{
            //     //新增
            //     JJZ.addData(tableName, obj, function (data) {
            //         window.location.href =JJZ.baseUrl+ '/' + tableName + '/cycleTaskDataGrid';
            //     });
            // }

            return false;
        });

        function initCron(cycleType) {
            var cron;
            var planTimeStr = JJZ.named('planTime').val();
            var planTime = new Date(planTimeStr);
            if (cycleType == 1) {
                //每天
                cron = String.format('0 {0} {1} * * ?', planTime.getMinutes(), planTime.getHours());
            } else if (cycleType == 2) {
                //每周 0表示星期日
                cron = String.format('0 {0} {1} ? * {2}', planTime.getMinutes(), planTime.getHours(), planTime.getDay());
            } else if (cycleType == 3) {
                //每月
                cron = String.format('0 {0} {1} {2} * ?', planTime.getMinutes(), planTime.getHours(), planTime.getDate());
            }else if (cycleType == 4) {
                //半年
                var month = planTime.getMonth()+1;
                if(month>6){
                    month = month-6;
                }
                cron = String.format('0 {0} {1} {2} {3}/6 ?', planTime.getMinutes(), planTime.getHours(),planTime.getDate(),month);
            } else if (cycleType == 5) {
                //一年
                cron = String.format('0 {0} {1} {2} {3} ?', planTime.getMinutes(), planTime.getHours(), planTime.getDate(),planTime.getMonth()+1);
            }
            return cron;
        }

        //获得编辑完成后的巡检计划内容
        function initCycleTaskContent() {
            var content = [];
            $("select[name='modelId'] option:selected").each(function (index, elem) {
                var temp = {};
                temp.modelId = $(elem).val();
                temp.modelName = $(elem).text();
                temp.deviceParts

                // var devicePartOption = $(elem).parent().parent().next().find('select[name="devicePartId"] option:selected');

                // temp.devicePartId = $(devicePartOption).val();
                // temp.devicePartName = $(devicePartOption).text();
                content.push(temp);

            });

            return JSON.stringify(content);
        }

        //用于初始化编辑时的巡检日期
        function initCycleTaskTime(cycleType, chekbox) {

        }

        //用于初始化编辑时的巡检计划信息
        function addOrderDetail(orderList) {
            var length = orderList.length;
            //先动态添加完成html
            for (var i = 1; i < length; i++) {
                var orderDiv = $('#order').clone();
                var detailIndex = $('div.orderDetails').length;
                $(orderDiv).removeAttr("id");
                $(orderDiv).prepend('<label class="layui-form-label"></label>');
                $(orderDiv).find('select[name="devicePartId"]').attr('index', detailIndex);
                $(orderDiv).find('select[name="modelId"]').attr('index', detailIndex);
                $(orderDiv).find('input[name="content"]').attr('index', detailIndex);
                $('div.orderDetails:last').after(orderDiv);
            }
            //初始化设备类型下拉框
            JJZ.initSelect(JJZ.named('modelId'), '/model/dataGrid', function (noError) {
                //在这里初始化接下来的指令
                if (noError) {
                    JJZ.named('modelId').find('option').each(function (index, elem) {
                        var tempElem = elem.outerHTML;
                        if (index != 0) {
                            for (var modelIndex = 1; modelIndex < length; modelIndex++) {
                                if ($(tempElem).val() == orderList[modelIndex].modelId) {
                                    var selectedOption = '<option value="' + $(tempElem).val() + '" selected="selected">' + $(tempElem).text() + '</option>';
                                    $('div.orderDetails').eq(modelIndex).find('select[name="modelId"]').append(selectedOption);
                                } else {
                                    $('div.orderDetails').eq(modelIndex).find('select[name="modelId"]').append(tempElem);
                                }
                            }
                        }
                        $(elem).val() == orderList[0].modelId ? $(elem).attr("selected", "selected") : '';
                    })

                }
            });
            //初始化设备部位下拉框
            JJZ.initSelect(JJZ.named('devicePartId'), '/devicePart/dataGrid', function (noError) {
                if (noError) {
                    JJZ.named('devicePartId').find('option').each(function (index, elem) {
                        var tempElem = elem.outerHTML;
                        if (index != 0) {
                            for (var partIndex = 1; partIndex < length; partIndex++) {
                                if ($(tempElem).val() == orderList[partIndex].devicePartId) {
                                    var selectedOption = '<option value="' + $(tempElem).val() + '" selected="selected">' + $(tempElem).text() + '</option>';
                                    $('div.orderDetails').eq(partIndex).find('select[name="devicePartId"]').append(selectedOption);
                                } else {
                                    $('div.orderDetails').eq(partIndex).find('select[name="devicePartId"]').append(tempElem);
                                }
                            }
                        }
                        $(elem).val() == orderList[0].devicePartId ? $(elem).attr("selected", "selected") : '';
                    })
                }
            });

            form.render();

        }

        JJZ.named('addOrder').click(function () {
            var orderDiv = $('#order').clone();
            var index = $('div.orderDetails').length;
            $(orderDiv).removeAttr("id");
            $(orderDiv).prepend('<label class="layui-form-label"></label>');

            $(orderDiv).find('select[name="modelId"] option:selected').removeAttr('selected');
            $(orderDiv).find('select[name="devicePartId"]').empty();
            $(orderDiv).find('select[name="devicePartId"]').append('<option value="">选择巡检部位</option>');
            $(orderDiv).find('select[name="devicePartId"]').attr('index', index);
            $(orderDiv).find('select[name="modelId"]').attr('index', index);
            $(orderDiv).find('input[name="content"]').val('');
            $(orderDiv).find('input[name="content"]').attr('index', index);
            $('div.orderDetails:last').after(orderDiv);
            form.render();
        });

        JJZ.named('deleteOrder').click(function () {

            if ($('div.orderDetails').length > 1) {
                $('div.orderDetails:last').remove();
                form.render();
            }
        })

    });


    String.prototype.format = function (args) {
        var result = this;
        if (arguments.length > 0) {
            if (arguments.length == 1 && typeof (args) == "object") {
                for (var key in args) {
                    if (args[key] != undefined) {
                        var reg = new RegExp("({" + key + "})", "g");
                        result = result.replace(reg, args[key]);
                    }
                }
            }
            else {
                for (var i = 0; i < arguments.length; i++) {
                    if (arguments[i] != undefined) {
                        //var reg = new RegExp("({[" + i + "]})", "g");//这个在索引大于9时会有问题，谢谢何以笙箫的指出
                        var reg = new RegExp("({)" + i + "(})", "g");
                        result = result.replace(reg, arguments[i]);
                    }
                }
            }
        }
        return result;
    }
    String.format = function () {
        if (arguments.length == 0)
            return null;

        var str = arguments[0];
        for (var i = 1; i < arguments.length; i++) {
            var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
            str = str.replace(re, arguments[i]);
        }
        return str;
    }

</script>
</body>
</html>